package com.bjpowernode.shop.config;

import com.bjpowernode.shop.constants.QueueConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    // 声明延迟队列
    @Bean
    public Queue orderMsgQueue() {
        Map<String, Object> arguments = new HashMap<>();
        // 消息死亡时间
        arguments.put("x-message-ttl", 30 * 1000);
        // 消息死亡后转发到哪个交换机
        arguments.put("x-dead-letter-exchange", QueueConstants.ORDER_DEAD_EX);
        // 消息死亡后转发到哪个路由key
        arguments.put("x-dead-letter-routing-key", QueueConstants.ORDER_DEAD_KEY);

        Queue queue = new Queue(
                QueueConstants.ORDER_MS_QUEUE,
                true, false, false, arguments
        );
        return queue;
    }

    // 死信队列、交换机的声明
    @Bean
    public Queue orderDeadQueue() {
        return new Queue(QueueConstants.ORDER_DEAD_QUEUE);
    }

    @Bean
    public DirectExchange orderDeadExchange() {
        return new DirectExchange(QueueConstants.ORDER_DEAD_EX);
    }

    @Bean
    public Binding orderDeadBinding() {
        return BindingBuilder.bind(orderDeadQueue()).to(orderDeadExchange()).with(QueueConstants.ORDER_DEAD_KEY);
    }
}
